<?php

namespace Shahu\Common\middleware;

use ReflectionException;
use Shahu\Common\common\jwtAuth\Auth;
use Shahu\Common\common\jwtAuth\Tenant;
use Shahu\Common\common\jwtAuth\Validate;
use Shahu\Common\exception\AuthException;
use Shahu\Common\exception\ValidateException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * Class StaticFile
 * @package app\middleware
 */
class CommonMiddleware implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws AuthException
     * @throws ReflectionException
     * @throws ValidateException
     */
    public function process(Request $request, callable $handler) : Response
    {
        //before
        $this->before($request);
        //controller
        $response = $handler($request); // 继续向洋葱芯穿越，直至执行控制器得到响应
        //after
        $this->after($request);

        return $response;
    }


    /**
     * @param Request $request
     * @return void
     * @throws AuthException
     * @throws ReflectionException
     * @throws ValidateException
     */
    private function before(Request $request) : void
    {
        //ip
        $GLOBALS['ip'] = ip2long($request->getRemoteIp());
        //租户
        $GLOBALS['tenant_id'] = $request->header('X-Tenant-Id');
        //检查租户
        Tenant::checkTenant();
        //检查权限
        Auth::checkAuthorization($request);
        //参数验证
        Validate::check($request);
    }


    private function after(Request $request)
    {

    }
}
